package com.stars.easyms.alarm.client;

import com.stars.easyms.base.constant.EasyMsCommonConstants;
import com.stars.easyms.base.util.EasyMsUtil;
import com.stars.easyms.base.util.JsonUtil;
import com.stars.easyms.base.util.ReflectUtil;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedHashMap;

/**
 * <p>className: BaseEasyMsAlarmClient</p>
 * <p>description: EasyMs告警客户端基础类</p>
 *
 * @author guoguifang
 * @version 1.7.0
 * @date 2020/11/26 5:25 下午
 */
public abstract class BaseEasyMsAlarmClient implements EasyMsAlarmClient {

    private String id;

    private final LinkedHashMap<String, String> alarmClientMap = new LinkedHashMap<>(8);

    private final EasyMsAlarmChannel easyMsAlarmChannel;

    protected BaseEasyMsAlarmClient(EasyMsAlarmChannel easyMsAlarmChannel, String id) {
        this.easyMsAlarmChannel = easyMsAlarmChannel;
        this.id = StringUtils.isBlank(id) ? EasyMsCommonConstants.DEFAULT : id;
    }

    @Override
    public EasyMsAlarmChannel getAlarmChannel() {
        return easyMsAlarmChannel;
    }

    @Override
    public String getClientId() {
        return id;
    }

    @Override
    public LinkedHashMap<String, String> getClientInfo() {
        if (alarmClientMap.isEmpty()) {
            Field[] declaredFields = this.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                if (!Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())
                        && !Modifier.isTransient(field.getModifiers()) && !EasyMsUtil.isTransientField(field)) {
                    String fieldName = field.getName();
                    Object obj = ReflectUtil.readFieldWithoutException(this, fieldName);
                    alarmClientMap.put(fieldName, JsonUtil.toJSONString(obj));
                }
            }
        }
        return alarmClientMap;
    }

}
